package com.xbell.dahua.demo.utils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
public class FfmpegUtil {

    private static final String DIR = "stream";

    @SneakyThrows
    public static void convertToHls(String filename, String targetName) {
        Path tsFilePath = Paths.get(DIR + "/" + filename).toAbsolutePath();
        Path segFilePath = Paths.get(DIR + "/" + filename.substring(0, filename.indexOf(".")) + "_seg_%03d.ts").toAbsolutePath();
        Path hlsFilePath = Paths.get(DIR + "/" + targetName).toAbsolutePath();
        // ffmpeg 命令
//        String command = String.format(
//                "Get-Content -Path '" + tsFilePath + "' -Wait -Encoding Byte | ffmpeg -re -fflags +genpts -i - -c copy -force_key_frames 'expr:gte(t,n_forced*5)' -hls_time 5  -hls_list_size 5 -hls_flags delete_segments+append_list -hls_segment_filename '%s' %s",
//                segFilePath, hlsFilePath
//        );
        String[] commands = {
                "ffmpeg",
                "-re",
                "-fflags", "+genpts",
                "-i", tsFilePath.toString(),
                "-c", "copy",
                "-force_key_frames", "expr:gte(t,n_forced*5)",
                "-hls_time", "5",
                "-hls_list_size", "5",
                "-hls_flags", "delete_segments+append_list",
                "-hls_segment_filename", segFilePath.toString(),
                hlsFilePath.toString()
        };
//        log.info("ffmpeg command: {}", command);
        try {
//            Process process = Runtime.getRuntime().exec(command);
//            int exitCode = process.waitFor();
//            log.info("ffmpeg exit code: {}", exitCode);


            // 创建子进程（以执行 "ls -l" 命令为例）
            ProcessBuilder pb = new ProcessBuilder(commands);
            pb.redirectErrorStream(true); // 合并错误输出和标准输出
            Process process = pb.start();

            // 获取子进程输出流（即子进程的标准输出）
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                log.info("ffmpeg process output: {}", line);
            }

            // 获取子进程输入流（即向子进程发送数据）
//            OutputStream outputStream = process.getOutputStream();
            // 若子进程需要输入，可以通过 outputStream 写入数据

            // 等待子进程执行完毕并获取返回值
            int exitCode = process.waitFor();
            log.info("ffmpeg process exit code: {}", exitCode);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
//            return false;
        }
    }

    public static void main(String[] args) {
        convertToHls("test.ts", "test.m3u8");
    }

}
